package com.onlookers.server;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DataInput extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("GBK");
		resp.getWriter().println("Hello BAE World!");
		EventService service = EventService.INSTANCE;
		
		String num = req.getParameter("num");
		if (num.equalsIgnoreCase("reset")) {
			service.reset();
			return;
		}
		String fileName = "init_news" + num + ".xml";
		File file = new File(fileName);
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// factory.setCoalescing(true);

		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(file);
			NodeList nodes = doc.getElementsByTagName("item");
			for (int i = 0; i < nodes.getLength(); i++) {
				Element element = (Element) nodes.item(i);
				String title = getCData(element, "title");
				String link = getCData(element, "link");
				String description = getCData(element, "description");
				String pubDate = getCData(element, "pubDate");
				String source = getCData(element, "source");
				String author = getCData(element, "author");

				Report report = new Report(title, link, description, pubDate,
						source, author);
				service.submit(report);
			}
			
			resp.getWriter().println(service.toString());
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}

	}

	public static String getCData(Element e, String name) {
		NodeList nodes = e.getElementsByTagName(name);
		Element value = (Element) nodes.item(0);
		return getCharacterDataFromElement(value);
	}

	public static String getCharacterDataFromElement(Element e) {
		Node child = e.getFirstChild();
		if (child instanceof CharacterData) {
			CharacterData cd = (CharacterData) child;
			return cd.getData();
		}
		return "";
	}

}
